#include "csapp.h"
typedef struct sockaddr SA;
void echo(int connfd){
	size_t n;
	char buf[MAXLINE];
	rio_t rio;
	Rio_readinitb(&rio,connfd);
	while(1){
		n=Rio_readlineb(&rio,buf,MAXLINE);
		if(n==0) break;
//		printf("Receive: %s\n",buf);
		fputs(buf,stdout);		
//		printf("server received %d bytes\n",(int)n);
		Rio_writen(connfd,buf,n);
	}
	return;
}
int main(int argc,char **argv){
	int listenfd,connfd;
	socklen_t clientlen;
	struct sockaddr_storage clientaddr;// Ensure the store is enough
	char client_hostname[MAXLINE],client_port[MAXLINE];
	if(argc!=2){//More than one input 
		fprintf(stderr,"usage:%s <port>\n",argv[0]);
		exit(0);
	}
	listenfd=Open_listenfd( atoi(argv[1]) );
	while(1){
		clientlen = sizeof(struct sockaddr_storage);
		connfd = Accept(listenfd,(SA *)&clientaddr,&clientlen);
		getnameinfo((SA *)&clientaddr,clientlen,client_hostname,MAXLINE,client_port,MAXLINE,0);
		printf("Connected to (%s,%s)\n",client_hostname,client_port);
		echo(connfd);
		close(connfd);
	}
	exit(0);

}
